package cn.yunhe.controller;

import cn.yunhe.entity.*;
import cn.yunhe.service.ExamPaperService;
import cn.yunhe.util.DateUtil;
import cn.yunhe.util.DocUtil;
import cn.yunhe.util.DownloadExamPaper;
import cn.yunhe.util.TemplateParseUtil;
import com.github.pagehelper.Page;
import freemarker.template.TemplateException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/ExamPage")
public class ExamPaperController {

    @Resource
    private ExamPaperService examPaperService;

    @RequiresPermissions("/view/exampaper-list.html")
    @RequestMapping("/toExamPaper.do")
    public void toExamPaper(HttpServletResponse response) throws IOException {
        response.sendRedirect("/view/exampaper-list.html");
    }

    /**
     * 根据知识点分类分页模糊查询试卷
     *
     * @param pageSize  页大小
     * @param pageNum   当前页
     * @param examPaper 考试相关信息
     * @return
     * @author guohanyu
     */
    @RequestMapping("/getExamPaperList")
    public Map queryUserByPage(int pageSize, int pageNum, ExamPaper examPaper, Integer fieldId, Integer pointId, String creatorNeed, String createTimeNeed) {
        Map map = new HashMap();
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        //传入时间处理
        if (createTimeNeed != null && !createTimeNeed.equals("")) {
            try {
                Date cTime = DateUtil.String2DateTime(createTimeNeed);
                map.put("createTime", cTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            map.put("createTime", createTimeNeed);
        }

        //封装数据
        map.put("creator", creatorNeed);
        map.put("fieldId", fieldId);
        map.put("pointId", pointId);
        map.put("examPaper", examPaper);
        Page page = examPaperService.getPapersByFieldAndPointAndName(map);
        map.put("page", page);
        map.put("totalPage", page.getPages());

        return map;

    }

    /**
     * 添加试卷
     *
     * @param contentKnowledgePoint 添加的知识点
     * @param examPaperName         试卷名称
     * @param passPoint             及格分
     * @param duration              考试时间
     * @param questionCount         多少试题
     * @param questionPoint         每道多少分
     * @param totalPoint            总分
     * @param field                 所属科目
     * @param pointId               所属分类
     * @return 郭瀚钰
     */
    @RequestMapping("/addExamPaper")
    public void addExamPaper(HttpSession session, Integer examPaperType, HttpServletResponse response, String contentKnowledgePoint, String examPaperName, Integer passPoint, Integer duration, Integer questionCount, Integer questionPoint, Integer totalPoint, Integer field, Integer pointId, Integer judgmentQuestionCount, Integer judgmentQuestionPoint) throws IOException {
        //创建Map封装数据
        Map<String, Object> map = new HashMap<String, Object>();
        //创建ExamPaper对象封装数据
        ExamPaper examPaper = new ExamPaper();
        examPaper.setName(examPaperName);
        examPaper.setPassPoint(passPoint);
        examPaper.setDuration(duration);
        examPaper.setTotalPoint(totalPoint);
        examPaper.setField(new Field(field));
        examPaper.setPoint(new Point(pointId));
        examPaper.setPaperType(examPaperType);
        examPaper.setCreateTime(new Date());
        examPaper.setQuestionCount(questionCount);
        examPaper.setJudgmentQuestionCount(judgmentQuestionCount);
        examPaper.setTotalQuestionCount(questionCount + judgmentQuestionCount);
        examPaper.setChooseQuestionTotalPoint(questionCount * questionPoint);
        examPaper.setJudgmentQuestionTotalPoint(judgmentQuestionCount * judgmentQuestionPoint);
        User user = (User)session.getAttribute("Curr_User");
        examPaper.setCreator(user.getTrueName());
        examPaper.setStatus(0);
        List<Integer> pointList = new ArrayList<>();

        if(contentKnowledgePoint!=null && !"".equals(contentKnowledgePoint)) {
            //知识点数组数据处理
            List<String> pointListString = Arrays.asList(contentKnowledgePoint.split(","));


            for (String pl : pointListString) {
                pointList.add(Integer.parseInt(pl));
                System.out.println(pl);
            }

        }else{
            pointList = null;
        }

        //封装入map传入后台
        map.put("examPaper", examPaper);
        map.put("questionCount", questionCount);
        map.put("questionPoint", questionPoint);
        map.put("judgmentQuestionCount", judgmentQuestionCount);
        map.put("judgmentQuestionPoint", judgmentQuestionPoint);
        map.put("pointList", pointList);
        map.put("field",field);

        //执行新增操作
        examPaperService.addExamPaper(map);
        response.sendRedirect("/view/exampaper-list.html");
    }

    /**
     * 访问试卷详情页面
     *
     * @param examPaperId
     * @return 郭瀚钰
     */
    @RequestMapping("/toShowExamPaper")
    public ModelAndView toShowExamPaper(Integer examPaperId) {
        ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
        System.out.println(examPaper.getJudgmentQuestionCount());
        return new ModelAndView("showExamPaper2", "examPaper", examPaper);
    }


    /**
     * 根据试卷Id获取试题,删选后置于试卷模板
     *
     * @param examPaperId
     * @return guohanyu
     */
    @RequestMapping("/getExamPaperAndItsQuestions")
    public Map<String, Object> getExamPaperAndItsQuestions(Integer examPaperId) {
        Map<String, Object> map = new HashMap<>();
        List<Question> allQuestionList = examPaperService.getQuestionsByExamPaperId(examPaperId);
        List<Question> questionList = new ArrayList<>();
        List<Question> judgmentQuestionList = new ArrayList<>();
        //筛选出选择题列表
        for (Question aql : allQuestionList) {
            if (aql.getQuestionType().getId() == 1) {
                questionList.add(aql);
            }
        }
        //筛选出判断题
        for (Question aql : allQuestionList) {
            if (aql.getQuestionType().getId() == 3) {
                judgmentQuestionList.add(aql);
            }
        }
        //封装题类型
        map.put("questionList", questionList);
        map.put("judgmentQuestionList", judgmentQuestionList);
        return map;
      /*  List<Question> questionList = examPaperService.getQuestionsByExamPaperId(examPaperId);
        return questionList;*/
    }


    /**
     * 根据传入试卷Id集合,批量删除或单个删除试卷
     *
     * @param
     * @param examPaperId 单个传入Id
     * @return
     */
    @RequestMapping("/delExamPaper")
    public Map delExamPaper(String examPaperIdsString, Integer examPaperId) {
        List<String> examPaperIds = Arrays.asList(examPaperIdsString.split(","));
        List<Integer> examPapersId = new ArrayList<>();
        if (examPaperIds.size() > 0) {
            for (String epi : examPaperIds) {
                examPapersId.add(Integer.parseInt(epi));
            }
        }

        examPapersId.add(examPaperId);
        Map<String, Object> map = new HashMap<>();
        boolean flag = false;
        try {
            flag = examPaperService.delExamPaperById(examPapersId);
        } catch (Exception e) {
            flag = false;
        }
        if (flag) {
            //删除成功
            map.put("flag", flag);
        } else {
            //删除失败
            map.put("flag", flag);
        }
        return map;
    }

    /**
     * 从试卷中移除题目
     *
     * @param examPaperId    试卷Id
     * @param questionId     试题Id
     * @param questionTypeId 试题类型Id
     * @return
     */
    @RequestMapping("/removeQuestionFromExamPaper")
    public Map<String, Object> removeQuestionFromExamPaper(Integer examPaperId, Integer questionId, Integer questionTypeId) {
        //封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("examPaperId", examPaperId);
        map.put("questionId", questionId);
        map.put("questionTypeId", questionTypeId);
        boolean flag = false;
        try {
            flag = examPaperService.removeQuestionFromExamPaper(map);
        } catch (Exception e) {
            flag = false;
        }
        if (flag) {
            //移除成功
            map.put("flag", flag);
        } else {
            //移除失败
            map.put("flag", flag);
        }
        return map;
    }

    /**
     * 教师添加试卷
     * @param session
     * @param examPaperType
     * @param response
     * @param examPaperName
     * @param passPoint
     * @param duration
     * @param questionCount
     * @param questionPoint
     * @param totalPoint
     * @param field
     * @param pointId
     * @param judgmentQuestionCount
     * @param judgmentQuestionPoint
     * @param chooseQuestion
     * @param judgementQuestion
     * @throws IOException
     */
    @RequestMapping("/addArtificialExamPaper")
    public void addArtificialExamPaper(HttpSession session, Integer examPaperType, HttpServletResponse response, String examPaperName, Integer passPoint, Integer duration, Integer questionCount, Integer questionPoint, Integer totalPoint, Integer field, Integer pointId, Integer judgmentQuestionCount, Integer judgmentQuestionPoint, String[] chooseQuestion, String[] judgementQuestion) throws IOException {
        //创建Map封装数据
        Map<String, Object> map = new HashMap<String, Object>();
        //创建ExamPaper对象封装数据
        ExamPaper examPaper = new ExamPaper();
        examPaper.setName(examPaperName);
        examPaper.setPassPoint(passPoint);
        examPaper.setDuration(duration);
        examPaper.setTotalPoint(totalPoint);
        examPaper.setField(new Field(field));
        examPaper.setPoint(new Point(0));
        examPaper.setPaperType(examPaperType);
        examPaper.setCreateTime(new Date());
        examPaper.setQuestionCount(questionCount);
        examPaper.setJudgmentQuestionCount(judgmentQuestionCount);
        examPaper.setTotalQuestionCount(questionCount + judgmentQuestionCount);
        examPaper.setChooseQuestionTotalPoint(questionCount * questionPoint);
        examPaper.setJudgmentQuestionTotalPoint(judgmentQuestionCount * judgmentQuestionPoint);
        User user = (User)session.getAttribute("Curr_User");
        examPaper.setCreator(user.getTrueName());
        examPaper.setStatus(0);

        //选择题数组转化为List
        List<Integer> chooseQuestionList = new ArrayList<>();
        if (chooseQuestion != null || (chooseQuestion != null && chooseQuestion.length != 0)) {
            List<String> chooseQuestionLists = Arrays.asList(chooseQuestion);

            for (String cql : chooseQuestionLists) {
                System.out.println();
                chooseQuestionList.add(Integer.parseInt(cql));
                System.out.println(cql);
            }
        } else {
            chooseQuestionList = new ArrayList<>();
        }

        //判断题数组转化为List
        List<Integer> judgementQuestionList = new ArrayList<>();
        if (judgementQuestion != null || (judgementQuestion != null && judgementQuestion.length != 0)) {
            List<String> judgementQuestionLists = Arrays.asList(judgementQuestion);

            for (String jql : judgementQuestionLists) {
                judgementQuestionList.add(Integer.parseInt(jql));
                System.out.println(jql);
            }

        } else {
            judgementQuestionList = new ArrayList<>();
        }
        //封装入map传入后台
        map.put("examPaper", examPaper);
        map.put("questionCount", questionCount);
        map.put("questionPoint", questionPoint);
        map.put("judgmentQuestionCount", judgmentQuestionCount);
        map.put("judgmentQuestionPoint", judgmentQuestionPoint);
        map.put("chooseQuestionList", chooseQuestionList);
        map.put("judgementQuestionList", judgementQuestionList);

        //执行新增操作
        examPaperService.addArtificialExamPaper(map);
        response.sendRedirect("/view/exampaper-list.html");
    }


  /*  @RequestMapping("/downloadExamPaper")
    public String downloadExamPaper(Integer examPaperId,HttpServletRequest request) {
        ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
        List<Question> allQuestionList = examPaperService.getQuestionsByExamPaperId(examPaperId);
        //获取项目路径
      *//*  File f = new File(this.getClass().getResource("/").getPath());
        System.out.println(f);*//*
        //生成文件
        String file = DownloadExamPaper.makePaper(examPaperId,allQuestionList,examPaper,"/usr/java/tom/webapps/ROOT/WEB-INF/classes");
        try {
            System.out.println(file);
            return (file);
        } catch (Exception e) {
            e.printStackTrace();
            return "123";
        }
    }*/

    @RequestMapping("/downloadExamPaper")
    public ModelAndView downloadExamPaper(Integer examPaperId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
        List<Question> allQuestionList = examPaperService.getQuestionsByExamPaperId(examPaperId);
        //构建数据
        Map<String, Object> data = new HashMap<>();
        List<Question> questionList = new ArrayList<>();
        List<Question> judgmentQuestionList = new ArrayList<>();
        //筛选出选择题列表
        for (Question aql : allQuestionList) {
            if (aql.getQuestionType().getId() == 1) {
                questionList.add(aql);
            }
        }
        //筛选出判断题
        for (Question aql : allQuestionList) {
            if (aql.getQuestionType().getId() == 3) {
                judgmentQuestionList.add(aql);
            }
        }
        //封装题类型
        data.put("examPaper", examPaper);
        data.put("chooseQuestions", questionList);
        data.put("judges", judgmentQuestionList);

        //生成文件
        File file = DocUtil.createDoc(data,this.getClass());
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;

        try {
            long fileLength = file.length();
            response.setContentType("application/msword");
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }


    @RequestMapping("/getPaperCount")
    public int getPaperCount() {
        return examPaperService.getPaperCount();
    }

    public ExamPaperService getExamPaperService() {
        return examPaperService;
    }

    public void setExamPaperService(ExamPaperService examPaperService) {
        this.examPaperService = examPaperService;
    }
}